﻿/// <reference path="../libs/jquery-1.8.2-vsdoc.js" />
var SCA = SCA || {};
SCA.UI = SCA.UI || {};
SCA.UI.ExplorerLocations = SCA.UI.ExplorerLocations || {};

SCA.UI.ExplorerLocations.Dialog = function (explorerLocationsTable) {
    this.explorerLocationsTable = explorerLocationsTable;
    this.DAL;
    this.siteAbsoluteUrl;

    //TODO: duplication
    var FOLDER_TYPE_WEB = "Sobiens.Connectors.Entities.SharePoint.SPWeb";
    var FOLDER_TYPE_LIST = " Sobiens.Connectors.Entities.SharePoint.SPList";
    var FOLDER_TYPE_FOLDER = "Sobiens.Connectors.Entities.SharePoint.SPFolder";

    //TODO: duplication
    var treeParams = treeParams || {};
    treeParams.allowSelectWeb = treeParams.allowSelectWeb || true;
    treeParams.allowSelectList = treeParams.allowSelectList || true;
    treeParams.allowSelectFolder = treeParams.allowSelectFolder || true;
    treeParams.allowSelectItem = treeParams.allowSelectItem || false;
    treeParams.exploreDepth = treeParams.exploreDepth || "Folder";

    var thisContext = this;
    var initialExplorerLocation;


    this.Setup = function() {
        GetDialog().on("dialogclose", function(event, ui) { jQuery(".validity-modal-msg").hide(); });
        GetDropDownSiteSetting().change(thisContext.LoadTreeForSiteSetting);
        
        GetRadioButtonLocationShowAll().change(ShowHideTree);
        GetRadioButtonLocationShowSelected().change(ShowHideTree);

    };

    var ShowHideTree = function () {
        var explorerLocationTree = jQuery("#tree2");
        if (GetSelectedRadioButtonLocation().val() == "All") {
            explorerLocationTree.hide();
        }
        else {
            explorerLocationTree.show()
        }
    }

    this.New = function () {
        GetHiddenInputIndex().val("-1");
        FillDropDownList(SCA.AppConfiguration.SiteSettings, GetDropDownSiteSetting(), function (item) { return item.ID; }, function (item) { return item.Url; });

        var siteSettingUrl = GetDropDownSiteSettingSelectedText();
        this.siteAbsoluteUrl = siteSettingUrl;

        GetCheckBoxGeneral().attr("checked", true);
        GetCheckBoxOutlook().attr("checked", true);
        GetCheckBoxWord().attr("checked", true);
        GetCheckBoxExcel().attr("checked", true);
        GetRadioButtonLocationShowAll().attr("checked", true);
        ShowHideTree();
        GetCheckBoxAllowSelectSubfolders().attr("checked", true);
        initialExplorerLocation = null;
        LoadTree(GetDropDownSiteSettingSelectedText(), new Array());
    }

    this.Load = function (index) {
        try {
            if ((SCA.AppConfiguration.ExplorerConfiguration == null) || (SCA.AppConfiguration.ExplorerConfiguration.ExplorerLocations == null))
                return;

            var explorerLocation = GetExplorerLocation(index);
            initialExplorerLocation = explorerLocation;

            FillDropDownList(SCA.AppConfiguration.SiteSettings, GetDropDownSiteSetting(), function (item) { return item.ID; }, function (item) { return item.Url; });
            GetDropDownSiteSetting().val(explorerLocation.SiteSettingID);

            GetCheckBoxGeneral().attr("checked", jQuery.inArray("General", explorerLocation.ApplicationTypes) != -1);
            GetCheckBoxOutlook().attr("checked", jQuery.inArray("Outlook", explorerLocation.ApplicationTypes) != -1);
            GetCheckBoxWord().attr("checked", jQuery.inArray("Word", explorerLocation.ApplicationTypes) != -1);
            GetCheckBoxExcel().attr("checked", jQuery.inArray("Excel", explorerLocation.ApplicationTypes) != -1);

            if (explorerLocation.ShowAll) {
                GetRadioButtonLocationShowAll().attr("checked", true);
            }
            else {
                GetRadioButtonLocationShowSelected().attr("checked", true);
            }

            ShowHideTree();

            GetCheckBoxAllowSelectSubfolders().attr("checked", explorerLocation.AllowToSelectSubfolders);

            this.LoadTreeForSiteSetting();

            GetHiddenInputIndex().val(index);
        }
        catch (ex) {
            console.error("SCA.UI.ExplorerLocations.Dialog - Load(): " + ex.message);
        }
    }
    

    this.LoadTreeForSiteSetting = function() {
        var siteSettingUrl = GetDropDownSiteSettingSelectedText();
        this.siteAbsoluteUrl = siteSettingUrl;

        LoadTree(siteSettingUrl, new Array());
    }


    var LoadTree = function(siteAbsoluteUrl, children)
    {
        thisContext.treeData = {
            title: siteAbsoluteUrl, isFolder: true, key: "rootNode", expand: true,
            children: children,
            hideCheckbox: false,
            unselectable: false,
        };

        var root = jQuery("#tree2").dynatree("getRoot");
        root.removeChildren();
        root.addChild(thisContext.treeData);

        GenerateTreeChildren();
    }


    var GenerateTreeChildren = function() //LoadTreeChildren
    {
        thisContext.DAL = new SCA.DAL.SP(thisContext.siteAbsoluteUrl);
        thisContext.DAL.Init(Function.createDelegate(thisContext, thisContext.onSuccess), Function.createDelegate(thisContext, thisContext.onFail));
    }


    this.onSuccess = function () {
        var rootNode = jQuery("#tree2").dynatree("getTree").getNodeByKey("rootNode");
        this.AddTreeChildren(rootNode, this.DAL.rootWeb.websCollection, this.DAL.rootWeb.listsCollection);
        
        jQuery("#tree2").dynatree("option", "onSelect", function (flag, node) {

            if (flag == true) {
                if (node.getLevel() != 1) {
                    node.getParent().select(true);
                }
            }
            else {
                var children = node.getChildren();
                if (children != null) {
                    for (var i = 0; i < children.length; i++) {
                        children[i].select(false);
                    }
                }
            }
        });

        //TODO: partial duplication
        jQuery("#tree2").dynatree("option", "onLazyRead", function (node) {
            //debugger;
            var entity = node.data.key;
            if (entity instanceof SCA.DAL.Web) {
                entity.Load(function () { thisContext.AddTreeChildren(node, entity.websCollection, entity.listsCollection); Recall(node); }, this.onFail);
            }
            else if (entity instanceof SCA.DAL.List) {
                entity.rootFolder.Load(function () { thisContext.AddFolderChildrenToTree(node, entity.rootFolder.subFolderAndItemCollection); Recall(node); }, this.onFail);
            }
            else if (entity instanceof SCA.DAL.Folder) {
                entity.Load(function () { thisContext.AddFolderChildrenToTree(node, entity.subFolderAndItemCollection); Recall(node); }, this.onFail);
            }
        });

        if (initialExplorerLocation == null)
        {
            return;
        }
            
        var rootFolder = initialExplorerLocation.BasicFolderDefinition;
        var rootFolderNode = FindRootFolderNode(rootNode);
        if (rootFolderNode != null) {
            FillInChildrenRecursive(rootFolder, rootFolderNode);
        }
    }

    var Recall = function(node)
    {
        if (node.Folder != null) { FillInChildrenRecursive(node.Folder, node); 
        }
    }


    var FindRootFolderNode = function(rootNode) //only in the root web (lists and sub webs), doesn't go deeper (to folders or lists of sub webs)
    {
        var rootFolder = initialExplorerLocation.BasicFolderDefinition;
        if (rootFolder == null)
            return null;
        var rootFolderUrl = rootFolder.FolderUrl;

        var rootFolderNode = FindRootNodeRecursive(rootFolderUrl, rootNode);
        if (rootFolderNode == null)
        {
            alert("didn't find any node with url: " + rootFolderUrl);
            return;
        }

        rootFolderNode.select(true);

        return rootFolderNode;
    }

    var FindRootNodeRecursive = function(rootFolderUrl, node)
    {
        if ((node.data.title.toLowerCase() === rootFolderUrl.toLowerCase()) || 
            ((node.data.key.absoluteUrl != null) && (node.data.key.absoluteUrl.toLowerCase() === rootFolderUrl.toLowerCase())))
        {
            return node;
        }
        else
        {
            for (var i = 0; i < node.childList.length; i++)
            {
                var result = FindRootNodeRecursive(rootFolderUrl, node.childList[i]);
                if(result != null)
                {
                    return result;
                }
            }
            return null;
        }
    }

    var FillInChildrenRecursive = function (folder, node) {
        var folderChildren = folder.Folders;
        if ((folderChildren == null || folderChildren.length == 0))
            return;

        var nodeChildren = node.childList;
        if (nodeChildren == null) {
            node.Folder = folder;
            node.expand();
            return;
        }

        node.Folder = null; //not to be called onLazyRead from user

        for (var i = 0; i < folderChildren.length; i++) {
            
            var folderChild = folderChildren[i];
            for (var j = 0; j < nodeChildren.length; j++) {
                var nodeChild = nodeChildren[j];
                FillInParentAndChildrenRecursive(folderChild, nodeChild);
            }
        }
    }
    

    var FillInParentAndChildrenRecursive = function (folder, node) {
        var entity = node.data.key;
        if (entity.absoluteUrl == null) {
            if (entity.title.toLowerCase() == folder.Title.toLowerCase()) { //if the absolute url is not loaded, needs to match by title to perform loading
                entity.Load(function () { FillInParentAndChildrenRecursive(folder, node) }); //load to get the abosluteUrl
            }
        }
        else {
            if (folder.FolderUrl.toLowerCase() === entity.absoluteUrl.toLowerCase()) {
                node.select(true);
                FillInChildrenRecursive(folder, node);
            }
        }
    }

    //TODO: duplication
    this.AddTreeChildren = function (node, websCollection, listsCollection) {
        var children = new Array();
        for (var i = 0 ; i < websCollection.length; i++) {
            var current = websCollection[i];
            var treeNode = {
                title: current.title,
                key: current,
                expand: false,
                hideCheckbox: !treeParams.allowSelectWeb,
                unselectable: !treeParams.allowSelectWeb,
                isLazy: (treeParams.exploreDepth == "List" || treeParams.exploreDepth == "Folder" || treeParams.exploreDepth == "Item")
            };
            children.push(treeNode);
        }

        for (var i = 0 ; i < listsCollection.length; i++) {
            var current = listsCollection[i];
            var treeNode = {
                title: current.title,
                key: current,
                expand: false,
                hideCheckbox: !treeParams.allowSelectList,
                unselectable: !treeParams.allowSelectList,
                isLazy: (treeParams.exploreDepth == "Folder" || treeParams.exploreDepth == "Item")
            };
            children.push(treeNode);
        }

        node.setLazyNodeStatus(DTNodeStatus_Ok);
        node.addChild(children);
    }

    //TODO: duplication
    this.AddFolderChildrenToTree = function (node, itemsCollection) {
        var children = new Array();
        for (var i = 0 ; i < itemsCollection.length; i++) {
            var current = itemsCollection[i];

            var treeNode = {
                title: current.title,
                key: current,
                expand: false
            };

            if (current instanceof SCA.DAL.Folder) {
                treeNode.hideCheckbox = !treeParams.allowSelectFolder;
                treeNode.isLazy = treeParams.exploreDepth == "Folder";
            }
            else {
                if (treeParams.exploreDepth != "Item") {
                    continue;
                }
                treeNode.hideCheckbox = !treeParams.allowSelectItem;
                treeNode.isLazy = false;
            }

            children.push(treeNode);
        }

        node.setLazyNodeStatus(DTNodeStatus_Ok);
        node.addChild(children);
    }


    this.onFail = function (data) {
        //debugger;
        alert("fail:" + data);
    }


    this.Validate = function () {

        jQuery.validity.setup({ outputMode: "modal" });

        jQuery.validity.start();
        
        //TODO: ...

        var result = jQuery.validity.end();

        return result.valid;
    }


    this.Close = function () {
        GetDialog().dialog("close");
    }

    this.Save = function () {

        var isValid = this.Validate();
        if (!isValid)
            return;

        var index = GetHiddenInputIndex().val();

        var isNewItem = false;
        if (index == -1) //it's a new explorer location
        {
            index = SCA.AppConfiguration.ExplorerConfiguration.ExplorerLocations.push({}) - 1;
            isNewItem = true;
        }

        var explorerLocation = GetExplorerLocation(index);

        explorerLocation.ApplicationTypes = new Array();
        if(GetCheckBoxGeneral().is(':checked')) {
            explorerLocation.ApplicationTypes.push("General");
        }

        if (GetCheckBoxOutlook().is(':checked')){
            explorerLocation.ApplicationTypes.push("Outlook");
        }
        if (GetCheckBoxExcel().is(':checked')) {
            explorerLocation.ApplicationTypes.push("Excel");
        }
        if (GetCheckBoxWord().is(':checked')) {
            explorerLocation.ApplicationTypes.push("Word");
        }

        explorerLocation.SiteSettingID = GetDropDownSiteSetting().val();
        explorerLocation.ShowAll = GetRadioButtonLocationShowAll().is(':checked');
        explorerLocation.AllowToSelectSubfolders = GetCheckBoxAllowSelectSubfolders().is(':checked');

        explorerLocation.BasicFolderDefinition = GetBasicFolderDefinitionFromTree();

        if (isNewItem) {
            this.explorerLocationsTable.AddRow(index);
            explorerLocation.ID = SP.Guid.newGuid().ToSerialized();
        }
        else {
            this.explorerLocationsTable.RefreshRow(index);
        }

        this.Close();
}


    var GetBasicFolderDefinitionFromTree = function(){
        var tree = jQuery("#tree2");
        
        if (GetRadioButtonLocationShowAll().is(':checked')) {
            return GetBasicFolderDefinitionFromTreeRootOnly();
        }
        
        var selectedNodes = tree.dynatree("getSelectedNodes");
        if(selectedNodes.length == 0)
            return null;
       
        var rootNode = tree.dynatree("getTree").getNodeByKey("rootNode");

        return GetBasicFolderDefinitionRecursive (rootNode, {});
    }
    
    var GetBasicFolderDefinitionFromTreeRootOnly = function () {
        var tree = jQuery("#tree2");
        
        var rootNode = tree.dynatree("getTree").getNodeByKey("rootNode");
        var folderNode = {
            SiteSettingID: GetDropDownSiteSetting().val(),
            Title: rootNode.data.title,
            FolderUrl: rootNode.data.title,
            FolderType:  FOLDER_TYPE_WEB
        }
        return folderNode;
    }

    var GetBasicFolderDefinitionRecursive = function(treeNode, folderNode)
    {
        if(!treeNode.isSelected())
            return null;
     
        folderNode.SiteSettingID = GetDropDownSiteSetting().val(); //TODO: cache this value
        folderNode.Folders = new Array();
        
        if (treeNode.getLevel() == 1)
        {
            folderNode.Title = treeNode.data.title;
            folderNode.FolderUrl = treeNode.data.title;
            folderNode.FolderType = FOLDER_TYPE_WEB;
        }
        else
        {
            var entity = treeNode.data.key;
            folderNode.Title = entity.title;
            folderNode.FolderUrl = entity.absoluteUrl;
            folderNode.FolderType = GetFolderType(entity);

            if (folderNode.FolderUrl == null) //node hasn't been fully loaded
            {
                entity.Load(function () { folderNode.FolderUrl = entity.absoluteUrl; }, this.onFail);
            }
        }

        var childNodes = treeNode.childList;

        if (childNodes == null)
            return folderNode;

        for (var i = 0 ; i < childNodes.length; i++) {
            var childNode = childNodes[i];
            var temp = GetBasicFolderDefinitionRecursive(childNode, {});
            if(temp!=null)
            {
                folderNode.Folders.push(temp);
            }
        }

        return folderNode;
    }
     

    var GetFolderType = function(entity)
    {
        if(entity instanceof SCA.DAL.Web)
            return FOLDER_TYPE_WEB;
        if(entity instanceof SCA.DAL.List)
            return FOLDER_TYPE_LIST;
        if(entity instanceof SCA.DAL.Folder)
            return FOLDER_TYPE_FOLDER;

        return null;
    }

    //TODO: duplicate
    var FillDropDownList = function (listOfItems, dropDownList, valueDelegate, textDelegate) {
        dropDownList.html("");

        if ((listOfItems != null) && (listOfItems.length > 0))
            for (var i = 0; i < listOfItems.length; i++) {
                var item = listOfItems[i];
                jQuery("<option value='" + valueDelegate(item) + "'>" + textDelegate(item) + "</option>").appendTo(dropDownList);
            }
    }


    var GetExplorerLocation = function (index) {
        return SCA.AppConfiguration.ExplorerConfiguration.ExplorerLocations[index];
    }

    var GetDropDownSiteSetting = function () {
        return jQuery("#DropDownExplorerLocationDialogSiteSettings");
    }

    var GetDropDownSiteSettingSelectedText = function () {
        return jQuery("#DropDownExplorerLocationDialogSiteSettings option:selected").text();
    }

    var GetCheckBoxGeneral = function () {
        return jQuery("#CheckBoxExplorerLocationDialogGeneral");
    }

    var GetCheckBoxOutlook = function () {
        return jQuery("#CheckBoxExplorerLocationDialogOutlook");
    }

    var GetCheckBoxWord = function () {
        return jQuery("#CheckBoxExplorerLocationDialogWord");
    }

    var GetCheckBoxExcel = function () {
        return jQuery("#CheckBoxExplorerLocationDialogExcel");
    }
 
    var GetRadioButtonLocationShowAll = function () {
        return jQuery("#RadioButtonExplorerLocationDialogShowAll");
    }

    var GetRadioButtonLocationShowSelected = function () {
        return jQuery("#RadioButtonExplorerLocationDialogShowSelected");
    }

    var GetSelectedRadioButtonLocation = function () {
        return jQuery("input[name=ExplorerLocationLocation]:checked");
    }

    var GetCheckBoxAllowSelectSubfolders = function () {
        return jQuery("#CheckBoxExplorerLocationDialogAllowSelectSubfolders");
    }

    var GetHiddenInputIndex = function () {
        return jQuery("#HiddenFieldExplorerLocationDialogCurrentIndex");
    }

    var GetDialog  = function()
    {
        return jQuery("#ExplorerLocationEditDialog");
    }

    this.Setup();

};